package com.dss.service;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.dss.dao.PreplanDAO;
import com.dss.po.Preplan;
import com.dss.vo.PreplanItem;
import com.infomanage.bean.FieldBean;
import com.infomanage.bean.PaginationBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.DeptDAO;
import com.infomanage.exception.DaoException;
import com.infomanage.po.Department;
import com.infomanage.po.User;
import com.infomanage.util.Consts;
import com.infomanage.util.FileUpload;
import com.infomanage.util.StringUtil;
import com.infomanage.util.TimeUtil;
import com.infomanage.util.smartupload.SmartRequest;
import com.infomanage.util.smartupload.SmartUpload;
import com.jiuqi.util.ReturnObject;
import com.jiuqi.util.StringUtils;

public class PreplanService {

	public static PreplanItem loadPreplanItem(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String itemId= request.getParameter("itemId");
			if(StringUtils.isEmpty(itemId)) return null;
			PreplanDAO dao = new PreplanDAO();
			return dao.find(Integer.parseInt(itemId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static List<PreplanItem> loadPreplanList(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			PreplanDAO dao = new PreplanDAO();
			return dao.findAll();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static ReturnObject savePreplan(
			SmartUpload smartUpload, User user) {
		SmartRequest request = smartUpload.getRequest();
		String[] fileNames = smartUpload.getFileNames();
		ReturnObject ret = new ReturnObject();
		try {
			Preplan bean = new Preplan();
			PreplanDAO dao = new PreplanDAO();
			String title = request.getParameter("title");
			bean.setTitle(title);
			if(fileNames != null && fileNames.length > 0){
				String storeName = fileNames[0].substring(fileNames[0].lastIndexOf("\\") + 1);
				bean.setStoreName(storeName);
			}
			bean.setDeptId(Integer.parseInt(request.getParameter("deptId")));
			bean.setTimestamp(TimeUtil.showCurrentDay());
			bean.setDescription(request.getParameter("description"));
			dao.add(bean);
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		
		}
		return ret;
	}
	
	private static ReturnObject modifyPreplan(
			SmartUpload smartUpload, User user){
		SmartRequest request = smartUpload.getRequest();
		String itemId = request.getParameter("itemId");
		String[] fileNames = smartUpload.getFileNames();
		ReturnObject ret = new ReturnObject();
		try {
			PreplanDAO dao = new PreplanDAO();
			Preplan bean = dao.find(Preplan.class, Integer.parseInt(itemId));
			if(fileNames != null && fileNames.length > 0){
				String storeName = fileNames[0].substring(fileNames[0].lastIndexOf("\\") + 1);
				bean.setStoreName(storeName);
			}
			bean.setTimestamp(TimeUtil.showCurrentDay());
			dao.modify(bean);
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		
		}
		return ret;
	}
	
	public static ReturnObject modifyPreplan(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int itemId = Integer.parseInt(request.getParameter("itemId"));
			PreplanDAO dao = new PreplanDAO();
			Preplan bean = dao.find(Preplan.class, itemId);
			bean.setDescription(request.getParameter("description"));
			bean.setTitle(request.getParameter("title"));
			bean.setDeptId(Integer.parseInt(request.getParameter("deptId")));
			dao.modify(bean);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		}
		return ret;
	}
	
	public static ReturnObject removePreplan(HttpServletRequest request, String itemId){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			if(itemId == null || "".equals(itemId)){
				itemId = request.getParameter("itemId");
			}
			PreplanDAO dao = new PreplanDAO();
			Preplan bean = dao.find(Preplan.class, Integer.parseInt(itemId));
			String storeName = bean.getStoreName();
			String path = request.getRealPath(Consts.FILE_UPLOAD_SAVE_DIR);
			dao.remove(Preplan.class, Integer.parseInt(itemId));
			File file = new File(path + "/" + storeName);
			file.delete();
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	
	public static ReturnObject operatePreplan(
			HttpServletRequest httpRequest, PageContext pageContext) {
		ReturnObject retObj = null;
		try {
			httpRequest.setCharacterEncoding("UTF-8");
			User user = (User)httpRequest.getSession().getAttribute(com.infomanage.util.Consts.LOGINED_USER);
			String actionType = httpRequest.getParameter("actionType");
			if (actionType == null) {
				FileUpload fileUpload = new FileUpload("doc,docx");
				SmartUpload smartUpload = fileUpload.upload(httpRequest,
						pageContext);
				SmartRequest request = smartUpload.getRequest();
				actionType = request.getParameter("actionType");
				if ("add".equals(actionType)) {
					retObj = savePreplan(smartUpload, user);
				}
				if ("modify".equals(actionType)) {
					retObj = modifyPreplan(smartUpload, user);
				}
			}else if("del".equals(actionType)){
				removePreplan(httpRequest, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			retObj.setErrorMessage(e.getMessage());
		}
		return retObj;
	}
	
	private static SearchBean buildSearchCondition(HttpServletRequest request, HttpServletResponse response,
			JspWriter out) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String title = request.getParameter("title");
		SearchBean searchBean = new SearchBean();
		if (!StringUtil.isEmpty(title)) {
			FieldBean field = new FieldBean("title", title);
			field.setLike(true);
			searchBean.add(field);
		}
		
		// 设置权限
//		User user = (User) request.getSession().getAttribute(Consts.LOGINED_USER);
//		if (user != null) {
//			AuthorityBean authority = new AuthorityBean();
//			authority.setRole(RoleType.valueOf(user.getRoleId()));
//			authority.setDeptId(user.getAssociatedDept());
//			searchBean.setAuthority(authority);
//		}
		return searchBean;
	}
	
	public static int getPageCount(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			PreplanDAO dao = new PreplanDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			return (dao.count(searchBean) + PaginationBean.pageSize - 1)/PaginationBean.pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	public static List<PreplanItem> search(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			PreplanDAO dao = new PreplanDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			//设置分页
			String currPageNum = request.getParameter("currPageNum");
			PaginationBean page = new PaginationBean();
			if(currPageNum == null){
				page.setCurrentPageNum(1);
			}else{
				page.setCurrentPageNum(Integer.parseInt(currPageNum));
				
			}
			searchBean.setPage(page);
			List<PreplanItem> list = dao.findByFields(searchBean);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static ReturnObject removeBatchPreplan(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String batchIds = request.getParameter("batchIds");
			PreplanDAO dao = new PreplanDAO();
			if(batchIds != null){
				String[] ids = batchIds.split(";");
				for(String id : ids){
					dao.remove(Preplan.class, Integer.parseInt(id));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage("删除失败！");
		}
		return ret;
	}
	
	public static String requestData(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			response.setContentType("text/xml;charset=utf-8");
			Element root = new Element("root");
			String ids = request.getParameter("ids");
			String[] idArray = ids.split(";");
			DeptDAO deptDAO = new DeptDAO();
			PreplanDAO preplanDAO = new PreplanDAO();
			for (String id : idArray) {
				if (!"".equals(id)) {
					Element deptaEle = new Element("dept");
					deptaEle.setAttribute("deptId", id);
					Department department = deptDAO.findById(Integer.parseInt(id));
					if(department == null){
						continue;
					}
					List<Preplan> preplanList = preplanDAO.findByDeptId(department.getDeptId());
					if(preplanList != null){
						for (Preplan preplan : preplanList) {
							Element preplanEle = new Element("preplan");
							preplanEle.setAttribute("preplanId", String.valueOf(preplan.getPreplanId()));
							preplanEle.setAttribute("preplanTitle", preplan.getTitle());
							preplanEle.setAttribute("prepalnStorename", preplan.getStoreName());
							deptaEle.addContent(preplanEle);
						}
					}
					deptaEle.setAttribute("deptName", department.getPath());
					root.addContent(deptaEle);
				}
			}
			Document doc = new Document(root);
			Format format = Format.getPrettyFormat();
			format.setEncoding("UTF-8");
			XMLOutputter output = new XMLOutputter(format);
			PrintWriter pw;
			pw = response.getWriter();
			output.output(doc, pw);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
